package com.bjh.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;

@Slf4j
@Configuration
public class ZkConfig {

    private ZkPropertiesSource zkPropertiesSource;

    //毫秒
    private  int timeout = 400000000;

    public ZkConfig(ZkPropertiesSource zkPropertiesSource) {
        this.zkPropertiesSource = zkPropertiesSource;
    }

    @Bean(name = "zooKeeperClient")
    public ZooKeeper zkClient(){
        ZooKeeper zooKeeper=null;
        try {
            //使一个线程等待其他线程各自执行完毕后在执行
            //使用在这边,zk连接需要时间,等待连接成功后在执行下面逻辑
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            //连接成功后，会回调watcher监听，此连接操作是异步的，执行完new语句后，直接调用后续代码
            zooKeeper = new ZooKeeper(zkPropertiesSource.getConnectString(), timeout, event -> {
                log.info("接受到watcher通知:{}",event);
                if(Watcher.Event.KeeperState.SyncConnected==event.getState()){
                    //如果收到了服务端的响应事件,连接成功
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
            log.info("【初始化ZooKeeper连接状态....】={}",zooKeeper.getState());

        }catch (Exception e){
            log.error("初始化ZooKeeper连接异常....】={}",e);
        }
        return  zooKeeper;
    }
}
